package com.crl.nfp.log.service;

import com.crl.nfp.util.ZuulConstUtil;
import com.crl.nfp.log.dao.LogDao;
import com.crl.nfp.log.model.LogModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * 日志入库
 *
 * @author 宋长军
 * @date 2020/4/9 15:52
 */
@Service
public class LogService {

    @Autowired
    private LogDao logDao;

    private final Logger LOGGER = LoggerFactory.getLogger("apiLog");

    /**
     * 请求日志入库
     *
     * @param logModel 日志信息
     */
    @Async(ZuulConstUtil.ZUUL_LOG_EXECUTOR)
    public void insertLog(LogModel logModel) {

        int logLength = 150, logSubLength = 140;
        try {
            String requestParam = logModel.getRequestParam();
            if (requestParam.length() > logLength) {
                logModel.setRequestParam(requestParam.substring(0, logSubLength).concat("... ..."));
            }
            logDao.insertLog(logModel);
        } catch (Exception e) {
            LOGGER.error("ERROR-网关入库日志异常！".concat(logModel.toSuccessString()), e);
        }
    }

    /**
     * 响应非200的日志
     *
     * @param logModel 日志信息
     */
    @Async(ZuulConstUtil.ZUUL_LOG_EXECUTOR)
    public void insertErrorLog(LogModel logModel) {

        try {
            logDao.insertErrorLog(logModel);
        } catch (Exception e) {
            LOGGER.error("ERROR-网关入库响应非200日志异常！".concat(logModel.toErrorString()), e);
        }
    }
}
